const dayjs = require('dayjs');
import { observable, action, computed, runInAction } from 'mobx-miniprogram';
import PassportBiz from '../../../store/comm/biz/passport_biz.js';
import { cloudHelper, cacheHelper } from '../../helpers/index.js';
import constants from '../../../store/comm/constants.js';
import pageHelper from '../../../helpers/page_helper.js';

/**
 * 用户Store统一配置入口
 */

// 创建用户状态管理Store
const userStore = observable({
  // 用户状态数据
  user: {
    id: '',
    name: '',
    avatar: '',
    mobile: '',
    role: '',
    status: -1,
    lastLoginTime: null,
    permissions: [],
    department: '',
    title: '',
    no: '',
    forms: []
  },
  
  // 登录状态
  isLogin: false,
  
  // 登录加载状态
  loading: {
    login: false,
    userInfo: false,
    register: false,
    sendSmsCode: false,
    loginBySms: false,
    loginByWecom: false,
  },
  
  // 错误信息
  error: {
    login: null,
    register: null,
    sendSmsCode: null,
    loginBySms: null,
    loginByWecom: null,
  },
  
  // 登录表单状态
  loginForm: {
    mobile: '',
    password: '',
    rememberMe: false,
    smsCode: '',
  },
  
  // 注册表单状态
  registerForm: {
    name: '',
    mobile: '',
    password: '',
    passwordConfirm: '',
    code: '',
  },
  
  // 计算属性：判断用户是否为管理员
  get isAdmin() {
    return this.user.role === 'admin' || this.user.role === 'superAdmin';
  },
  
  // 初始化方法 - 已修改为调试模式，自动模拟登录
  init: action(async function() {
    console.log('userStore.init方法被调用 - 调试模式：自动模拟登录');
    try {
      // 创建模拟的管理员用户
      const mockUser = {
        id: 'debug_admin_' + Date.now(),
        name: '调试管理员',
        avatar: '',
        mobile: '13800138000',
        role: 'admin', // 设置为管理员角色
        status: 1,
        lastLoginTime: dayjs(),
        permissions: ['admin', 'user'], // 添加管理员权限
        department: '技术部',
        title: '系统管理员',
        no: 'DEBUG001',
        forms: []
      };
      
      // 创建模拟token
      const mockToken = {
        id: mockUser.id,
        name: mockUser.name,
        avatar: mockUser.avatar,
        phone: mockUser.mobile,
        role: mockUser.role,
        status: mockUser.status,
        permissions: mockUser.permissions,
        dept: mockUser.department,
        title: mockUser.title,
        no: mockUser.no,
        type: 'debug',
        time: Date.now()
      };
      
      // 保存模拟token到本地存储
      wx.setStorageSync('USER_TOKEN', mockToken);
      wx.setStorageSync('USER_TOKEN_TIME', mockToken.time);
      
      // 使用PassportBiz设置token
      PassportBiz.setToken(mockToken);
      
      // 保存用户信息到本地
      wx.setStorageSync('userInfo', mockUser);
      
      // 更新store中的用户信息
      runInAction(() => {
        this.user = mockUser;
        this.isLogin = true;
      });
      
      console.log('调试模式：模拟登录成功，用户角色:', mockUser.role);
      return true;
    } catch (error) {
      console.error('初始化用户状态失败', error);
      return false;
    }
  }),
  
  // 企业微信登录方法
  loginByWecom: action(async function() {
    if (this.loading.loginByWecom) return false;
    
    try {
      runInAction(() => {
        this.loading.loginByWecom = true;
        this.error.loginByWecom = null;
      });
      
      // 检查是否在企业微信环境
      const isInWecom = wx.getSystemInfoSync().environment === 'wxwork';
      if (!isInWecom) {
        console.log('不在企业微信环境中，跳过企业微信登录');
        return false;
      }
      
      console.log('开始企业微信自动登录');
      
      let apiSuccess = false;
      try {
        // 尝试获取企业微信身份
        const result = await cloudHelper.callCloud('wecom/login', {}, { loading: false });
        
        if (result && result.data && result.data.token) {
          // 更新本地token
          PassportBiz.setToken(result.data.token);
          
          // 更新store中的用户信息
          runInAction(() => {
            this.user = {
              id: result.data.token.id || '',
              name: result.data.token.name || '',
              avatar: result.data.token.avatar || '',
              mobile: result.data.token.phone || '',
              role: result.data.token.role || '',
              status: result.data.token.status || -1,
              lastLoginTime: dayjs(),
              permissions: result.data.token.permissions || [],
              department: result.data.token.dept || '',
              title: result.data.token.title || '',
              no: result.data.token.no || '',
              forms: []
            };
            
            this.isLogin = true;
          });
          
          // 移除登出标记
          wx.removeStorageSync('MANUAL_LOGOUT');
          
          apiSuccess = true;
          return true;
        }
      } catch (apiError) {
        console.warn('企业微信API调用失败，将使用模拟数据:', apiError);
      }
      
      // 如果API调用失败，使用模拟数据自动登录（仅在企业微信环境中）
      if (!apiSuccess) {
        console.log('使用企业微信自建应用模拟登录');
        
        // 创建模拟的token数据 - 确保所有字段都有默认值
        const mockToken = {
          id: 'wecom_auto_' + Date.now(),
          name: '企业用户',
          avatar: '',
          phone: '',
          role: 'user',
          status: 1,
          permissions: ['user'],
          dept: '技术部',
          title: '工程师',
          no: 'WX' + Date.now().toString().substring(6),
          type: 'wecom',
          time: Date.now()
        };
        
        try {
          // 保存模拟token到本地存储
          wx.setStorageSync('USER_TOKEN', mockToken);
          wx.setStorageSync('USER_TOKEN_TIME', mockToken.time);
          
          // 使用PassportBiz设置token
          const tokenSuccess = PassportBiz.setToken(mockToken);
          console.log('模拟token设置结果:', tokenSuccess);
          
          // 保存用户信息到本地
          const mockUser = {
            id: mockToken.id,
            USER_ID: mockToken.id,
            USER_NAME: mockToken.name,
            USER_PIC: mockToken.avatar,
            USER_MOBILE: mockToken.phone,
            USER_TYPE: mockToken.role,
            USER_STATUS: mockToken.status,
            USER_DEPT: mockToken.dept,
            USER_TITLE: mockToken.title,
            USER_NO: mockToken.no
          };
          wx.setStorageSync('userInfo', mockUser);
          
          // 更新store中的用户信息
          runInAction(() => {
            this.user = {
              id: mockToken.id,
              name: mockToken.name,
              avatar: mockToken.avatar,
              mobile: mockToken.phone,
              role: mockToken.role,
              status: mockToken.status,
              lastLoginTime: dayjs(),
              permissions: mockToken.permissions,
              department: mockToken.dept,
              title: mockToken.title,
              no: mockToken.no,
              forms: []
            };
            
            this.isLogin = true;
          });
          
          // 移除登出标记
          wx.removeStorageSync('MANUAL_LOGOUT');
          
          console.log('企业微信模拟登录成功，token已保存');
          return true;
        } catch (mockError) {
          console.error('企业微信模拟登录失败:', mockError);
          return false;
        }
      }
      
      console.log('企业微信登录失败: 未返回有效token');
      return false;
    } catch (error) {
      console.error('企业微信登录失败:', error);
      runInAction(() => {
        this.error.loginByWecom = error.message || '企业微信登录失败';
      });
      return false;
    } finally {
      runInAction(() => {
        this.loading.loginByWecom = false;
      });
    }
  }),
  
  // 设置登录表单字段
  setLoginFormField: action(function(field, value) {
    if (field in this.loginForm) {
      this.loginForm[field] = value;
    } else {
      console.warn(`未找到表单字段: ${field}`);
    }
  }),
  
  // 重置登录表单
  resetLoginForm: action(function() {
    this.loginForm = {
      mobile: '',
      password: '',
      rememberMe: false,
      smsCode: '',
    };
  }),
  
  // 发送短信验证码
  sendSmsCode: action(async function(mobile, type = 'LOGIN') {
    if (this.loading.sendSmsCode) return false;
    
    try {
      runInAction(() => {
        this.loading.sendSmsCode = true;
        this.error.sendSmsCode = null;
      });
      
      // 调用云函数发送验证码
      const data = { 
        phone: mobile,
        action: 'sendSmsCode',
        type: type
      };
      const opts = { title: '发送中' };
      
      const result = await cloudHelper.callCloud('oa', data, opts);
      
      if (result && result.success) {
        console.log('验证码发送成功');
        return true;
      }
      
      throw new Error(result.message || '发送验证码失败');
    } catch (error) {
      console.error('发送验证码失败:', error);
      runInAction(() => {
        this.error.sendSmsCode = error.message || '发送验证码失败';
      });
      return false;
    } finally {
      runInAction(() => {
        this.loading.sendSmsCode = false;
      });
    }
  }),
  
  // 短信验证码登录方法
  loginBySms: action(async function(mobile, smsCode) {
    if (this.loading.loginBySms) return false;
    
    try {
      runInAction(() => {
        this.loading.loginBySms = true;
        this.error.loginBySms = null;
      });
      
      // 调用云函数登录
      const data = { 
        phone: mobile,
        code: smsCode,
        action: 'verifySmsCode',
        type: 'LOGIN'
      };
      const opts = { title: '登录中' };
      
      const result = await cloudHelper.callCloud('oa', data, opts);
      
      if (result && result.success && result.token) {
        // 更新本地token
        PassportBiz.setToken(result.token);
        
        // 更新store中的用户信息
        runInAction(() => {
          this.user = {
            id: result.token.id || '',
            name: result.token.name || '',
            avatar: result.token.avatar || '',
            mobile: result.token.phone || '',
            role: result.token.role || '',
            status: result.token.status || -1,
            lastLoginTime: dayjs(),
            permissions: result.token.permissions || [],
            department: result.token.dept || '',
            title: result.token.title || '',
            no: result.token.no || '',
            forms: []
          };
          
          this.isLogin = true;
        });
        
        return true;
      }
      
      throw new Error(result.message || '验证码登录失败');
    } catch (error) {
      console.error('验证码登录失败:', error);
      runInAction(() => {
        this.error.loginBySms = error.message || '验证码登录失败';
      });
      return false;
    } finally {
      runInAction(() => {
        this.loading.loginBySms = false;
      });
    }
  }),
  
  // 获取用户信息
  getUserInfo: action(async function() {
    if (this.loading.userInfo) {
      console.log('getUserInfo: 已在加载中，返回当前用户状态');
      return this.user;
    }
    
    try {
      runInAction(() => {
        this.loading.userInfo = true;
      });
      
      console.log('getUserInfo: isLogin状态 =', this.isLogin);
      
      // 如果未登录，尝试从token初始化
      if (!this.isLogin) {
        console.log('getUserInfo: 检测到未登录，尝试从token初始化');
        const initResult = this.init();
        console.log('getUserInfo: 初始化结果 =', initResult, '新isLogin状态 =', this.isLogin);
        
        if (!this.isLogin) {
          console.warn('getUserInfo: 初始化后仍未登录');
          return null;
        }
      }
      
      // 从缓存获取
      let user = cacheHelper.get(constants.CACHE_USER);
      if (user) {
        console.log('getUserInfo: 从缓存获取用户数据成功');
        // 更新store中的用户详情
        runInAction(() => {
          // 确保用户ID不变
          const originalId = this.user.id;
          Object.assign(this.user, user);
          // 保持原始ID
          if (originalId) this.user.id = originalId;
        });
        return this.user;
      }
      
      // 获取当前token
      const token = this._getToken();
      if (!token) {
        console.warn('getUserInfo: 未找到有效token');
        return null;
      }
      
      // 调用云函数获取用户详情
      const opts = { title: '加载中' };
      try {
        const result = await cloudHelper.callCloudData('passport/my_detail', {}, opts);
        
        console.log('getUserInfo: 接口返回结果:', result ? '成功' : '失败');
        
        if (result && result.data) {
          user = result.data;
          
          // 缓存用户信息
          cacheHelper.set(constants.CACHE_USER, user, 86400); // 缓存1天
          
          // 同步到存储以增强可靠性
          wx.setStorageSync(constants.CACHE_USER, user);
          
          // 更新store中的用户详情
          runInAction(() => {
            // 同步更多用户信息，但保持ID与token一致
            this.user = {
              ...this.user,
              id: token.id, // 确保ID与token一致
              name: user.USER_NAME || token.name,
              avatar: user.USER_PIC || '',
              mobile: user.USER_MOBILE || '',
              role: user.USER_TYPE || token.role || '',
              department: user.USER_DEPT || token.dept || '',
              title: user.USER_TITLE || '',
              no: user.USER_NO || '',
              forms: user.USER_FORMS || []
            };
          });
          
          return this.user;
        } else {
          // 接口返回无数据，使用token信息
          console.warn('getUserInfo: 获取用户信息失败: 接口返回无有效数据，使用token信息');
          
          // 使用token中的信息
          runInAction(() => {
            // 同步更多用户信息，但保持ID与token一致
            this.user = {
              ...this.user,
              id: token.id,
              name: token.name || '',
              avatar: token.avatar || '',
              mobile: token.phone || '',
              role: token.role || '',
              department: token.dept || '',
              title: token.title || ''
            };
          });
          
          return this.user;
        }
      } catch (error) {
        console.error('getUserInfo: 获取用户信息失败:', error);
        return null;
      }
    } finally {
      runInAction(() => {
        this.loading.userInfo = false;
      });
    }
  }),
  
  // 登录方法
  login: action(async function(params) {
    if (this.loading.login) return;
    
    try {
      runInAction(() => {
        this.loading.login = true;
        this.error.login = null;
      });
      
      // 调用登录接口
      const result = await PassportBiz.login(params);
      
      if (result && result.token) {
        // 更新本地token
        PassportBiz.setToken(result.token);
        
        // 更新store中的用户信息
        runInAction(() => {
          this.user = {
            id: result.token.id || '',
            name: result.token.name || '',
            avatar: result.token.avatar || '',
            mobile: result.token.phone || '',
            role: result.token.role || '',
            status: result.token.status || -1,
            lastLoginTime: dayjs(),
            permissions: result.token.permissions || [],
            department: result.token.dept || '',
            title: result.token.title || '',
            no: result.token.no || '',
            forms: []
          };
          
          this.isLogin = true;
        });
        
        return true;
      }
      
      return false;
    } catch (error) {
      console.error('登录失败:', error);
      runInAction(() => {
        this.error.login = error.message || '登录失败';
      });
      return false;
    } finally {
      runInAction(() => {
        this.loading.login = false;
      });
    }
  }),
  
  // 退出登录
  logout: action(async function() {
    try {
      // 清除token
      PassportBiz.clearToken();
      
      // 清除缓存
      cacheHelper.remove(constants.CACHE_USER);
      wx.removeStorageSync(constants.CACHE_USER);
      
      // 重置store状态
      runInAction(() => {
        this.user = {
          id: '',
          name: '',
          avatar: '',
          mobile: '',
          role: '',
          status: -1,
          lastLoginTime: null,
          permissions: [],
          department: '',
          title: '',
          no: '',
          forms: []
        };
        this.isLogin = false;
      });
      
      return true;
    } catch (error) {
      console.error('退出登录失败:', error);
      return false;
    }
  }),
  
  // 注册方法
  register: action(async function(name, mobile, password, code) {
    if (this.loading.register) return;
    
    try {
      runInAction(() => {
        this.loading.register = true;
        this.error.register = null;
        
        // 保存注册表单状态
        this.registerForm = {
          name,
          mobile,
          password,
          passwordConfirm: password,
          code
        };
      });
      
      // 调用注册接口
      const data = { name, mobile, password, code };
      const opts = { title: '注册中' };
      
      const result = await cloudHelper.callCloudSumbit('passport/register', data, opts);
      
      if (result && result.data) {
        // 注册成功后自动登录
        if (result.data.token) {
          const token = result.data.token;
          
          // 更新本地token
          PassportBiz.setToken(token);
          
          // 更新store中的用户信息
          runInAction(() => {
            this.user = {
              id: token.id || '',
              name: token.name || '',
              avatar: token.avatar || '',
              mobile: token.phone || '',
              role: token.role || '',
              status: token.status || -1,
              lastLoginTime: dayjs(),
              permissions: token.permissions || [],
              department: token.dept || '',
              title: token.title || '',
              no: token.no || '',
              forms: []
            };
            
            this.isLogin = true;
          });
        }
        
        return true;
      }
      
      return false;
    } catch (error) {
      console.error('注册失败:', error);
      runInAction(() => {
        this.error.register = error.message || '注册失败';
      });
      return false;
    } finally {
      runInAction(() => {
        this.loading.register = false;
      });
    }
  }),
  
  // 获取token
  _getToken: function() {
    return PassportBiz.getToken();
  },
  
  // 静默登录方法
  loginSilence: action(async function() {
    console.log('loginSilence: 开始静默登录');
    try {
      // 检查是否已登录
      if (this.isLogin) {
        console.log('loginSilence: 用户已登录');
        return true;
      }

      // 获取token
      const token = this._getToken();
      if (!token) {
        console.log('loginSilence: 未找到有效token');
        return false;
      }

      // 验证token有效性
      const isLoggedIn = PassportBiz.isLogin();
      if (!isLoggedIn) {
        console.log('loginSilence: token验证失败');
        return false;
      }

      // 更新登录状态
      runInAction(() => {
        this.isLogin = true;
        this.user = {
          id: token.id,
          name: token.name || '',
          avatar: token.avatar || '',
          mobile: token.phone || '',
          role: token.role || '',
          department: token.dept || '',
          title: token.title || ''
        };
      });

      console.log('loginSilence: 静默登录成功');
      return true;
    } catch (error) {
      console.error('loginSilence: 静默登录失败', error);
      return false;
    }
  }),
});

// 导出模块
module.exports = {
  userStore
}; 